package com.home.fansea.websocket;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.home.fansea.config.WebSocketConfigurator;
import com.home.fansea.entity.Message;
import com.home.fansea.entity.SystemMsg;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ServerEndpoint(value = "/chat",configurator = WebSocketConfigurator.class)
@Component
@Data
public class ChatEndPoint {

//    private static Set<ChatEndPoint> webSocketSet = new HashSet<>();
    private static Map<String,ChatEndPoint> webSocketMap = new HashMap<>();

    //和某个客户端连接对象，需要通过他来给客户端发送数据
    private Session session;

    //httpSession中存储着当前登录的用户名
    private HttpSession httpSession;


    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("__________________________________________");
        //获取客户端发送来的数据  {"toName":"fansea","message":"你好"}
        System.out.println("接收的消息是：" + message);
        Message messageObj = BeanUtil.copyProperties(message, Message.class);
        /*服务端 --> 客户端
        系统消息格式：{“isSystem”:true,“fromName”:null,“message”：[“李四”,“王五”]}
        推送给某一个的消息格式：{“isSystem”:false,“fromName”:“张三”,“message”：“你好”}*/
        String userName = (String) httpSession.getAttribute("userName");
        System.out.println("发送消息用户："+userName);
        SystemMsg systemMsg = new SystemMsg();
        System.out.println("messageObj.message:"+messageObj.getMessage());
        systemMsg.setMessage(messageObj.getMessage());
        systemMsg.setFromName(userName);
        String systemMsgJson = JSON.toJSONString(systemMsg);
        System.out.println("系统消息转发消息：" + systemMsgJson);
        //将消息发送给对应的用户
//        System.out.println(webSocketMap.get(messageObj.getToName()).getSession());
        webSocketMap.get(messageObj.getToName()).getSession().getBasicRemote().sendText(systemMsgJson);
    }

    @OnOpen
    public void onOpen(Session session,EndpointConfig config) {
        httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        //获取httpSession中存储的用户名
        this.session = session;
        String userName = (String) httpSession.getAttribute("userName");
        System.out.println("..........................."+userName+"连接建立成功.........................");
        System.out.println("用户名：" + userName);
        //将用户名和session存入map中
        webSocketMap.put(userName,this);

    }

    @OnClose
    public void onClose(Session seesion) {
        System.out.println("连接关闭了。。。");
    }

    @OnError
    public void onError(Session session,Throwable error) {
        System.out.println("出错了。。。。" + error.getMessage());
    }
}
